package com.taobao.askwho.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

public class ToolUtil {
	public static final Logger logger = Logger.getLogger(ToolUtil.class);
	/*
	 * MD5加密函数，使用UTF-8加密
	 */
	public static byte[] getMD5FromBytes(byte[] data) {
		if (data != null && data.length > 0) {
			try {
				MessageDigest md5 = MessageDigest.getInstance("MD5");
				return new BigInteger(1, md5.digest(data)).toString(32).getBytes(
						"UTF-8");
			} catch (NoSuchAlgorithmException e) {
				logger.error("初始化MD5编码类失败!" + e);
			} catch (UnsupportedEncodingException e) {
				logger.error("UTF-8编码不存在!" + e);
			}
		}
		return null;
	}
	/**
	 * 将16位byte[] 转换为32位String
	 * 
	 * @param buffer
	 * @return
	 */
	private static String toHex(byte buffer[]) {
		StringBuffer sb = new StringBuffer(buffer.length * 2);
		for (int i = 0; i < buffer.length; i++) {
			sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 15, 16));
		}
		return sb.toString();
	}	

	public static String getMD5_32String(String targetString) {
		if (targetString == null)
			return null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(targetString.getBytes());
			return toHex(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			logger.error("初始化MD5编码类失败!" + e);
		}		
		return null;
	}	

	/*
	 * 对给定的String进行Md5加密，并返回加密后生成的等长的字符串
	 */
	public static String getMD5String(String targetString) {
		if (targetString == null)
			return null;
		try {
			final String charsetName = "UTF-8";
			byte[] md5Data = getMD5FromBytes(targetString.getBytes(charsetName));
			if (md5Data == null)
				return null;

			return new String(md5Data, charsetName);
		} catch (UnsupportedEncodingException e) {
			logger.error("UTF-8编码不存在!" + e);
		}
		return null;
	}

	/**
	 * 如果方法有回调，添加回调的方法名
	 * @param origin
	 * @param callback
	 * @return
	 */
	public static String addCallBackString(String origin, String callback) {
		String strReturn = callback + "(";
		strReturn += origin;
		strReturn += ")";
		return strReturn;
	}
}
